package cn.miju.ser.common.rocketmq.consumer;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.miju.common.util.OkHttpUtil;
import cn.miju.database.constant.DbConstant;
import cn.miju.database.entity.Merchant;
import cn.miju.database.entity.PayOrder;
import cn.miju.database.service.MerchantDataService;
import cn.miju.database.service.PayOrderDataService;
import cn.miju.ser.common.rocketmq.Topic;
import cn.miju.ser.framework.request.MiJuPayRequest;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.MessageListener;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * <pre>
 * 订单支付结果通知接入方
 * </pre>
 *
 * @author zhuming
 * @version 1.0.0
 * @since 2023-03-13 10:29
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(topic = Topic.PAY_RESULT_NOTIFY_TOPIC, consumerGroup = "${rocketmq.producer.group}")
public class PayResultNotifyListener implements RocketMQListener<Long>, MessageListener {

    private final PayOrderDataService payOrderDataService;
    private final MerchantDataService merchantDataService;

    @Override
    public void onMessage(Long payOrderId) {
        PayOrder payOrder = payOrderDataService.getById(payOrderId);
        if (Objects.nonNull(payOrder)) {
            Merchant merchant = merchantDataService.getOne(new LambdaQueryWrapper<Merchant>().
                    select(Merchant::getPlatformMerchantNo, Merchant::getPayNotifyUrl).
                    eq(Merchant::getId, payOrder.getMerchantId()).
                    eq(Merchant::getMerchantType, payOrder.getPayWay()));
            JSONObject jsonParam = new JSONObject();
            jsonParam.put("out_trade_no", payOrder.getOutTradeNo());
            jsonParam.put("trade_no", merchant.isToMerchantTradeNo() ? payOrder.getTradeNo() : payOrder.getPlatTradeNo());
            jsonParam.put("total_amount", payOrder.getPayAmount());
            jsonParam.put("trade_status", DbConstant.PayOrderStatus.SUCCESS.equals(payOrder.getStatus()) ? "success" : "fail");
            jsonParam.put("pay_finish_time", payOrder.getPayOrderTime() == null ? null : payOrder.getPayOrderTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
            // 向接入方发送订单支付成功通知
            MiJuPayRequest miJuPayRequest = new MiJuPayRequest();
            miJuPayRequest.setPlatformMerchantNo(merchant.getPlatformMerchantNo());
            miJuPayRequest.setTimeStamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
            miJuPayRequest.setTransSerialNo(miJuPayRequest.getTimeStamp() + RandomUtil.randomInt(1000, 10000));
            miJuPayRequest.setEncrypt(false);
            miJuPayRequest.setBizContent(jsonParam.toString());
            JSONObject signJson = JSONObject.parseObject(JSONObject.toJSONString(miJuPayRequest));
            String sign = SecureUtil.md5(signJson.toString());
            miJuPayRequest.setSign(sign);
            OkHttpUtil.doPostJson(merchant.getPayNotifyUrl(), JSONObject.toJSONString(miJuPayRequest));
        }
    }

}
